package bx.com.smartcashier.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import bx.com.smartcashier.R;
import bx.com.smartcashier.config.ServerUrl;
import bx.com.smartcashier.receiver.DownloadReceiver;
import bx.com.smartcashier.utils.DownloadManagerUtil;
import bx.com.smartcashier.utils.JsonUtils;
import bx.com.smartcashier.utils.MyDateUtils;
import bx.com.smartcashier.utils.StringUtils;

import static bx.com.smartcashier.application.BxApplication.addActivity;
import static bx.com.smartcashier.application.BxApplication.removeActivity;


/**
 * 登陆界面
 * Created by admin on 2019/01/16.
 */
public class WelcomeActivity extends Activity {
    Button button_login;
    EditText editText_phoneNvm ,editText_passWord;
//    View view001, view002;
    public static Context mContext;
    public static SoundPool soundPool;
    public static HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();
    private String localVersion;
    private String version;
    private String url;
    private DownloadManagerUtil downloadManagerUtil;
    private long downloadId;
    private boolean isRegisterReceiver;
    private String updateContent;
    private DownloadManager downloadManager;
    private boolean isDownnload;
    private int[] bytesAndStatus=new int[3];
    private final int PROCESS_INT=109;
    @SuppressLint("HandlerLeak")
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case PROCESS_INT:
                    if(progressDialog!=null){
                        int[] ss= (int[]) msg.obj;
                        progressDialog.setProgress(ss[0]*100/ss[1]);
                    }
                    break;
            }


            super.handleMessage(msg);
        }
    };
    private ProgressDialog progressDialog;
//    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        addActivity(this);
        mContext = this;
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            return;
        }
        editText_passWord = (EditText) findViewById(R.id.edit_passWord);
        editText_phoneNvm = (EditText) findViewById(R.id.edit_phoneNvm);
        button_login = (Button) findViewById(R.id.button_login);
//        view001 = findViewById(R.id.view001);
//        view002 =  findViewById(R.id.view002);

        button_login.setOnClickListener(onClickListener);


        editText_passWord.setOnFocusChangeListener(AllFocusListener);
        editText_phoneNvm.setOnFocusChangeListener(AllFocusListener);

        SharedPreferences sharedPreferences = getSharedPreferences("User", 0);
        String Fusername = sharedPreferences.getString("PhoneNO", null);
        String Fpwd = sharedPreferences.getString("Fpwd", null);
        editText_phoneNvm.setText(Fusername);
        editText_passWord.setText(Fpwd);
//        getLocalAppVersion();
//        getAppVersions();



    }

    /**
     * 是否需要更新app
     */
    private void ifNeedUpdate() {
        if(StringUtils.isNotEmpty(localVersion)&&StringUtils.isNotEmpty(version)){
            if(Float.parseFloat(localVersion)<Float.parseFloat(version)){
                showALert();
            }
        }
    }

    /**
     * 更新app
     */
    private void updateApp() {
        isDownnload=true;
        Date date=new Date();
        String title="burent"+version;
        String desc="天豚，一个企业管理的方式";
        String name="burent_"+date.toString()+".apk";
        setReceiver(name,isDownnload);
        downloadManagerUtil = new DownloadManagerUtil(this);
        if (downloadId != 0) {
            downloadManagerUtil.clearCurrentTask(downloadId);
        }
        downloadId = downloadManagerUtil.download(url, title, desc,name);
        downloadManager=downloadManagerUtil.getDownloadManager();

        UpProgresThread thread=new UpProgresThread();
        thread.start();
    }


    public class UpProgresThread extends Thread {



        @Override
        public void run() {
            if (downloadManager != null && downloadId != 0) {
                DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
                Cursor cursor = null;
                try {
                    while(isDownnload) {

                        cursor = downloadManager.query(query);
                        if (cursor != null && cursor.moveToFirst()) {
                            //已经下载文件大小
                            bytesAndStatus[0] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                            //下载文件的总大小
                            bytesAndStatus[1] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                            //下载状态
                            bytesAndStatus[2] = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        }
                        Message msg=new Message();
                        msg.what=PROCESS_INT;
                        msg.obj=bytesAndStatus;
                        handler.sendMessage(msg);
                    }

                }catch (Exception e){

                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }
            super.run();
        }
    }
    /**
     * 显示更新对话框
     */
    private void showALert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(WelcomeActivity.this);
        builder.setTitle("发现新版本");
        String[] xx=updateContent.split("\\\\n");
        builder.setAdapter(
                new ArrayAdapter<String>(WelcomeActivity.this,
                        R.layout.alert_item, R.id.tv_item, xx),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {

                    }
                });
        //点击对话框以外的区域是否让对话框消失
        builder.setCancelable(true);
        //设置正面按钮
        builder.setNegativeButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                updateApp();
                progressDialog=new ProgressDialog(WelcomeActivity.this);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.show();
                dialog.dismiss();
            }
        });
        //设置反面按钮
        builder.setPositiveButton("稍后更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
            }
        });
        //显示对话框

        builder.create().show();

    }

    /**
     * 注册下载成功的广播监听
     */
    private void setReceiver(String name, Boolean isDownnload) {
        if (!isRegisterReceiver) {
            DownloadReceiver receiver = new DownloadReceiver(name,isDownnload);
            IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            intentFilter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
            this.registerReceiver(receiver, intentFilter);
            isRegisterReceiver = true;
        }
    }

    /**
     * 获取本地的安装版本
     */
    private void getLocalAppVersion() {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(),0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        localVersion = packInfo.versionName;
    }

    /**
     * 获取版本信息
     */
    private void getAppVersions() {


        RequestQueue requestQueue = Volley.newRequestQueue(this);

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                ServerUrl.url + "/api/login/getVersion.json",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        s = s.replace(" ","");
                        Map<String,Object> map = JsonUtils.getMap(s);
                        if(String.valueOf(map.get("code")).equals("000000"))
                        {
                            Map<String,Object> map_data = JsonUtils.getMap(String.valueOf(map.get("data")));
                            updateContent= String.valueOf(map_data.get("updateContent"));
                            version=String.valueOf(map_data.get("version"));
                            url=String.valueOf(map_data.get("url"));
                            ifNeedUpdate();
                        }
                        else
                        {
                            Toast.makeText(WelcomeActivity.this, "获取更新信息异常!", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(WelcomeActivity.this, "获取更新信息异常!", Toast.LENGTH_SHORT).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();

                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(60*1000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }

    private View.OnFocusChangeListener AllFocusListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            switch (v.getId())
            {
                case R.id.edit_passWord:
//                    view002.setBackgroundColor(Color.rgb(51, 153, 255));
//                    view001.setBackgroundColor(Color.rgb(230, 230, 230));
                    break;
                case R.id.edit_phoneNvm:
//                    view001.setBackgroundColor(Color.rgb(51, 153, 255));
//                    view002.setBackgroundColor(Color.rgb(230, 230, 230));
                    break;
            }
        }
    };

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_login://登录按钮
                    String userName = editText_phoneNvm.getText().toString().trim();
                    String passWord = editText_passWord.getText().toString().trim();

                    loadDate_phone(userName, passWord);

                    break;
            }
        }
    };
    public static String sToken = "";
    public static String sCompanyId = "";
    public static String sDistributorId = "";
    public static String sFlag = "";
    public static String shopId = "";

    public void loadDate_phone(final String phoneNo, final String password){
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                ServerUrl.url + "/api/login/login.json",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {

                        s = s.replace(" ","");
                        Map<String,Object> map = JsonUtils.getMap(s);

                        if(String.valueOf(map.get("code")).equals("000000"))
                        {
                            SharedPreferences sharedPreferences = WelcomeActivity.this.getSharedPreferences("User", 0);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("PhoneNO", editText_phoneNvm.getText().toString().trim());
                            editor.putString("Fpwd", editText_passWord.getText().toString().trim());

                            Map<String,Object> map_data = JsonUtils.getMap(String.valueOf(map.get("data")));
                            sToken = String.valueOf(map_data.get("token"));
                            MyDateUtils.setToken(sToken);

                            sCompanyId = String.valueOf(map_data.get("companyId"));
                            sDistributorId = String.valueOf(map_data.get("distributorId"));
                            shopId = String.valueOf(map_data.get("shopId"));
                            editor.putString("shopId", shopId);
                            editor.putString("token", sToken);
                            editor.commit();
                            sFlag = String.valueOf(map_data.get("tag"));
                            Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.setClass(WelcomeActivity.this, HomeActivity.class);
                            startActivity(intent);
                            removeActivity(WelcomeActivity.this);
                            finish();
                        }
                        else
                        {
                            Toast.makeText(mContext, map.get("msg").toString(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(mContext,volleyError.toString(),Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("phone", phoneNo);
                map.put("password", password);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(60*1000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }

    public static void playSound(final int id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                soundPool.play(soundMap.get(id), 1, 1, 1, 0, 1f);
            }
        }).start();
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            soundPool.release();
//            soundMap.clear();
//            MyActivityManager.removeActivity_(this);
//        }
//        return false;
//    }


    long startTime =0;
    long endTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            endTime = System.currentTimeMillis();
            if(endTime - startTime > 2000){
                Toast.makeText(this,"再次点击退出", Toast.LENGTH_SHORT).show();
            }else {
                //finish();
//                soundPool.release();
//                soundMap.clear();
                finish();
            }
            startTime = System.currentTimeMillis();
        }
        return false;
    }


}
